import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Animated,
  Dimensions,
} from 'react-native';
import { colors, shadows, spacing } from '../../styles';
import Icon from '../../components/Icon';
import { useDeck } from './DeckContext';
import { Deck, Card, ReviewRating } from './types';
import { useRoute, useNavigation } from '@react-navigation/native';

const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');

const ReviewScreen: React.FC = () => {
  const route = useRoute();
  const navigation = useNavigation();
  const { deck } = route.params as { deck: Deck };
  const { reviewCard, getDueCards } = useDeck();
  const [dueCards, setDueCards] = useState<Card[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isFlipped, setIsFlipped] = useState(false);
  const [flipAnimation] = useState(new Animated.Value(0));
  const [reviewedCount, setReviewedCount] = useState(0);
  const onExit = () => navigation.goBack();

  useEffect(() => {
    const cards = getDueCards(deck.id);
    setDueCards(cards);
  }, [deck.id]);

  const currentCard = dueCards[currentIndex];

  const flipCard = () => {
    if (isFlipped) {
      Animated.spring(flipAnimation, {
        toValue: 0,
        useNativeDriver: true,
      }).start();
    } else {
      Animated.spring(flipAnimation, {
        toValue: 180,
        useNativeDriver: true,
      }).start();
    }
    setIsFlipped(!isFlipped);
  };

  const handleReview = (rating: ReviewRating) => {
    if (!currentCard) return;

    reviewCard(deck.id, currentCard.id, rating);
    setReviewedCount(reviewedCount + 1);

    if (currentIndex < dueCards.length - 1) {
      setCurrentIndex(currentIndex + 1);
      setIsFlipped(false);
      flipAnimation.setValue(0);
    } else {
      // 复习完成
      onExit();
    }
  };

  const frontInterpolate = flipAnimation.interpolate({
    inputRange: [0, 180],
    outputRange: ['0deg', '180deg'],
  });

  const backInterpolate = flipAnimation.interpolate({
    inputRange: [0, 180],
    outputRange: ['180deg', '360deg'],
  });

  const frontOpacity = flipAnimation.interpolate({
    inputRange: [0, 90, 90],
    outputRange: [1, 1, 0],
  });

  const backOpacity = flipAnimation.interpolate({
    inputRange: [90, 90, 180],
    outputRange: [0, 1, 1],
  });

  if (!currentCard || dueCards.length === 0) {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{deck.name}</Text>
        </View>
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>没有需要复习的卡片</Text>
          <TouchableOpacity style={styles.doneButton} onPress={onExit}>
            <Text style={styles.doneButtonText}>返回</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  const progress = ((currentIndex + 1) / dueCards.length) * 100;

  return (
    <View style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>{deck.name}</Text>
      </View>

      {/* Progress */}
      <View style={styles.progressContainer}>
        <View style={styles.progressBar}>
          <View style={[styles.progressFill, { width: `${progress}%` }]} />
        </View>
        <Text style={styles.progressText}>
          {currentIndex + 1} / {dueCards.length}
        </Text>
      </View>

      {/* Card */}
      <View style={styles.cardContainer}>
        <TouchableOpacity
          activeOpacity={0.9}
          onPress={flipCard}
          style={styles.cardTouchable}
        >
          <Animated.View
            style={[
              styles.card,
              styles.cardFront,
              {
                transform: [{ rotateY: frontInterpolate }],
                opacity: frontOpacity,
              },
            ]}
          >
            <Text style={styles.cardLabel}>问题</Text>
            <Text style={styles.cardText}>{currentCard.front}</Text>
            <Text style={styles.tapHint}>点击查看答案</Text>
          </Animated.View>

          <Animated.View
            style={[
              styles.card,
              styles.cardBack,
              {
                transform: [{ rotateY: backInterpolate }],
                opacity: backOpacity,
              },
            ]}
          >
            <Text style={styles.cardLabel}>答案</Text>
            <Text style={styles.cardText}>{currentCard.back}</Text>
          </Animated.View>
        </TouchableOpacity>
      </View>

      {/* Rating Buttons */}
      {isFlipped && (
        <View style={styles.ratingContainer}>
          <Text style={styles.ratingTitle}>你记住了吗？</Text>
          <View style={styles.ratingButtons}>
            <TouchableOpacity
              style={[styles.ratingButton, styles.ratingAgain]}
              onPress={() => handleReview(ReviewRating.Again)}
            >
              <Text style={styles.ratingButtonText}>忘了</Text>
              <Text style={styles.ratingButtonSubText}>&lt;1分钟</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.ratingButton, styles.ratingHard]}
              onPress={() => handleReview(ReviewRating.Hard)}
            >
              <Text style={styles.ratingButtonText}>困难</Text>
              <Text style={styles.ratingButtonSubText}>&lt;10分钟</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.ratingButton, styles.ratingGood]}
              onPress={() => handleReview(ReviewRating.Good)}
            >
              <Text style={styles.ratingButtonText}>良好</Text>
              <Text style={styles.ratingButtonSubText}>4天</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.ratingButton, styles.ratingEasy]}
              onPress={() => handleReview(ReviewRating.Easy)}
            >
              <Text style={styles.ratingButtonText}>容易</Text>
              <Text style={styles.ratingButtonSubText}>7天</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: spacing.padding.lg,
  },
  closeButton: {
    padding: 8,
    width: 40,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text.primary,
  },
  progressContainer: {
    padding: spacing.padding.lg,
  },
  progressBar: {
    height: 8,
    backgroundColor: colors.surface,
    borderRadius: 4,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: colors.primary,
  },
  progressText: {
    marginTop: 8,
    fontSize: 14,
    color: colors.text.secondary,
    textAlign: 'center',
  },
  cardContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: spacing.padding.lg,
  },
  cardTouchable: {
    width: '100%',
    height: SCREEN_HEIGHT * 0.5,
  },
  card: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    backgroundColor: colors.surface,
    borderRadius: 16,
    padding: spacing.padding.xl,
    justifyContent: 'center',
    alignItems: 'center',
    backfaceVisibility: 'hidden',
    ...shadows.lg,
  },
  cardFront: {
    zIndex: 2,
  },
  cardBack: {
    zIndex: 1,
  },
  cardLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.primary,
    marginBottom: 16,
    textTransform: 'uppercase',
  },
  cardText: {
    fontSize: 24,
    color: colors.text.primary,
    textAlign: 'center',
    lineHeight: 32,
  },
  tapHint: {
    position: 'absolute',
    bottom: 24,
    fontSize: 14,
    color: colors.text.tertiary,
  },
  ratingContainer: {
    padding: spacing.padding.lg,
    backgroundColor: colors.surface,
    ...shadows.sm,
  },
  ratingTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text.primary,
    textAlign: 'center',
    marginBottom: 16,
  },
  ratingButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  ratingButton: {
    flex: 1,
    marginHorizontal: 4,
    paddingVertical: 12,
    paddingHorizontal: 8,
    borderRadius: 8,
    alignItems: 'center',
    ...shadows.sm,
  },
  ratingAgain: {
    backgroundColor: colors.danger,
  },
  ratingHard: {
    backgroundColor: colors.warning,
  },
  ratingGood: {
    backgroundColor: colors.success,
  },
  ratingEasy: {
    backgroundColor: colors.primary,
  },
  ratingButtonText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#fff',
    marginBottom: 4,
  },
  ratingButtonSubText: {
    fontSize: 11,
    color: 'rgba(255, 255, 255, 0.8)',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyText: {
    fontSize: 18,
    color: colors.text.secondary,
    marginBottom: 24,
  },
  doneButton: {
    backgroundColor: colors.primary,
    paddingHorizontal: 32,
    paddingVertical: 12,
    borderRadius: 8,
  },
  doneButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

export default ReviewScreen;
